package com.wosiliujing.learning.dict.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wosiliujing.learning.dict.entity.SysDict;
import com.wosiliujing.learning.annotation.SysLog;
import com.wosiliujing.learning.constant.CommonConstants;
import com.wosiliujing.learning.dict.service.SysDictService;
import com.wosiliujing.learning.util.RestResult;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/****
 *
 * @author 刘靖
 * @date 2019/5/19 23:16
 */
@RestController
@RequestMapping("/dict")
@AllArgsConstructor
public class SysDictController {

    private final SysDictService sysDictService;

    /**
     * 分页数据
     * @param page 分页参数
     * @param sysDict 查询条件
     * @return 分页数据
     */
    @GetMapping("/page")
    public RestResult page(Page<SysDict> page, SysDict sysDict){
        return RestResult.data(sysDictService.page(page,Wrappers.query(sysDict)));
    }

    /**
     * 通过类型查找字典
     * @param type 类型
     * @return 数据字典数据
     */
    @GetMapping("/type/{type}")
    public RestResult getByType(@PathVariable String type){
        return  RestResult.data(sysDictService.getOne(Wrappers.<SysDict>lambdaQuery().eq(SysDict::getType,type)));
    }

    /**
     * 保存数据字典
     * @param sysDict 数据字典
     * @return 保存结果
     */
    @SysLog("保存数据字典")
    @PreAuthorize("@pms.hasPermisssion('sys_dict_add')")
    @PostMapping("/save")
    public RestResult save(@RequestBody SysDict sysDict){
        sysDict.setCreateTime(LocalDateTime.now());
        sysDict.setDelFlag(CommonConstants.NORMAL_STATUS);
        return sysDictService.save(sysDict)? RestResult.ok(): RestResult.error(CommonConstants.SAVE_FAIL);
    }

    /**
     * 更新数据字典
     * @param sysDto 数据字典数据
     * @return 更新结果
     */
    @SysLog("更新数据字典")
    @PreAuthorize("@pms.hasPermisssion('sys_dict_edit')")
    @PutMapping("/update")
    public RestResult update(@RequestBody SysDict sysDto){
        SysDict sysDict = sysDictService.getById(sysDto.getId());
        BeanUtils.copyProperties(sysDto,sysDto);
        sysDict.setUpdateTime(LocalDateTime.now());
        return sysDictService.updateById(sysDict)? RestResult.ok(): RestResult.error(CommonConstants.DELETE_FAIL);
    }


    /**
     * 删除字典
     * @param id 字典id
     * @return 删除结果
     */
    @SysLog("删除字典")
    @PreAuthorize("@pms.hasPermisssion('sys_dict_del')")
    @DeleteMapping("/delete/{id}")
    public RestResult delete(@PathVariable String id){
        return sysDictService.removeById(id)? RestResult.ok(): RestResult.error(CommonConstants.DELETE_FAIL);
    }

}
